package org.zero.concurrency.demo.example.atomic;

import lombok.extern.slf4j.Slf4j;
import org.zero.concurrency.demo.annotations.ThreadSafe;

import java.util.concurrent.atomic.AtomicReference;

/**
 * @program: concurrency-demo
 * @description:
 * @author: 01
 * @create: 2018-10-15 22:39
 **/
@Slf4j
@ThreadSafe
public class AtomicExample4 {

    private static AtomicReference<Integer> count = new AtomicReference<>(0);

    public static void main(String[] args) {
        // 期望值为0时，更新为2
        count.compareAndSet(0, 2);  // 更新为2
        // 期望值为0时，更新为1
        count.compareAndSet(0, 1);  // 不会执行
        // 期望值为1时，更新为3
        count.compareAndSet(1, 3);  // 不会执行
        // 期望值为2时，更新为4
        count.compareAndSet(2, 4);  // 更新为4
        // 期望值为3时，更新为5
        count.compareAndSet(3, 5);  // 不会执行

        // 输出结果为4
        log.info("count:{}", count.get());
    }
}
